﻿using System.Drawing;

namespace LearnDSHeap;

public class Heaps
{
    private int[] data;
    private int maxSize;
    private int cSize;

    public Heaps()
    {
        maxSize = 10;
        data = new int[maxSize];
        cSize = 0;
        for (int i = 0; i < data.Length; i++)
        {
            data[i] = -1;
        }
    }

    public int Length()
    {
        return cSize;
    }

    public bool IsEmpty()
    {
        return cSize == 0;
    }

    public void Insert(int e)
    {
        if (cSize == maxSize)
        {
            Console.WriteLine("No Sapce in Heap");
            return;
        }

        cSize = cSize + 1;
        int hi = cSize;
        while (hi > 1 && e > data[hi / 2])
        {
            data[hi] = data[hi / 2];
            hi = hi / 2;
        }

        data[hi] = e;
    }

    public int GetMax()
    {
        if (IsEmpty())
        {
            Console.WriteLine("Heap is Empty");
            return -1;
        }

        return data[1];
    }

    public void Display()
    {
        for (int i = 0; i < data.Length; i++)
        {
            Console.WriteLine(data[i] + " ");
        }

        Console.WriteLine();
    }

    public int DeleteMax()
    {
        if (IsEmpty())
        {
            Console.WriteLine("Heap is Empty");
            return -1;
        }

        int e = data[1];
        data[1] = data[cSize];
        data[cSize] = -1;
        cSize = cSize - 1;
        int i = 1;
        int j = i * 2;
        while (j <= cSize)
        {
            if (data[j] < data[j + 1])
            {
                j++;
            }

            if (data[i] < data[j])
            {
                int temp = data[i];
                data[i] = data[j];
                data[j] = temp;
                i = j;
                j = i * 2;
            }
            else
            {
                break;
            }
        }

        return e;
    }
}